<template>
  <div class="app-container">
    <!-- 课程信息表单 -->
    <el-form
      :rules="rules"
      :model="courseInfo"
      ref="courseForm"
      label-width="80px"
      label-position="right"
    >
      <el-form-item label="课程标题" prop="title">
        <el-input v-model="courseInfo.title"
                  style="width: 400px"
                  placeholder="例如：Java从入门到精通"
        />
        <span class="tip">专业名词注意大小写</span>
      </el-form-item>
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师" prop="teacherId">
        <el-select
          clearable
          filterable
          v-model="courseInfo.teacherId"
          style="width: 140px"
          placeholder="请选择讲师"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>
      <!-- 所属科目 级联选择器 -->
      <el-form-item label="所属科目" prop="subjectIds">
        <el-cascader
          clearable
          v-model="courseInfo.subjectIds"
          :options="subjectList"
          :props="subjectProps"
          placeholder="请选择科目"
          @change="subjectChanged"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="课程简介">
        <tinymce :height="150" :width="800" v-model="courseInfo.description"/>
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :before-upload="beforeCoverUpload"
          :on-success="handleCoverSuccess"
          :on-error="handleCoverError"
          ref="upload"
          class="cover-uploader"
          :action="uploadAction"
        >
          <el-image v-if="courseInfo.cover" :src="courseInfo.cover" fit="cover"/>
          <i v-else class="el-icon-plus cover-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" style="width: 140px"
        />
      </el-form-item>
      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" style="width: 140px">
          <template slot="append">元</template>
        </el-input-number>
        <span class="tip">免费课程设置为 0 元</span>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <div style="text-align:center">
      <div v-if="this.$parent.courseId">
        <el-button :disabled="saveBtnDisabled" type="primary" size="medium" @click="updateAndNext()">
          保存更改<i class="el-icon-arrow-right el-icon--right"/>
        </el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" size="medium" @click="next()">
          下一步<i class="el-icon-arrow-right el-icon--right"/>
        </el-button>
      </div>
      <el-button v-else :disabled="saveBtnDisabled" type="primary" size="medium" @click="saveAndNext()">
        保存课程信息<i class="el-icon-arrow-right el-icon--right"/>
      </el-button>
    </div>
  </div>
</template>

<script>
import { courseApi, subjectApi, teacherApi } from '@/api'
// 富文本编辑器
import Tinymce from '@/components/Tinymce'

export default {
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false, // 按钮是否禁用
      rules: {
        title: [{ required: true, message: '请输入课程标题', trigger: 'blur' }],
        teacherId: [{ required: true, message: '请选择讲师', trigger: 'change' }],
        subjectIds: [{ type: 'array', required: true, message: '请选择科目', trigger: 'change' }]
      },
      courseInfo: { // 表单数据
        price: 0,
        lessonNum: 0,
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: '',
        subjectIds: [] // 级联选择器返回数组
      },
      teacherList: [], // 讲师列表
      subjectList: [], // 科目列表
      subjectProps: {
        value: 'id',
        label: 'title',
        children: 'children',
        expandTrigger: 'hover'
      }, // 自定义级联选择器选项
      uploadAction: process.env.VUE_APP_BASE_API + '/admin/aliyun/oss/cover/'
    }
  },
  created() {
    this.fetchTeacherList()
    this.fetchSubjectList()
    // 课程信息回显
    if (this.$parent.courseId) {
      this.fetchCourse(this.$parent.courseId)
    }
  },
  methods: {
    // 获取讲师列表
    fetchTeacherList() {
      teacherApi.queryAll().then(response => {
        this.teacherList = response.data.items
      })
    },
    // 获取科目列表
    fetchSubjectList() {
      subjectApi.getTreeList().then(response => {
        this.subjectList = this.modifySubjectList(response.data.items)
      })
    },
    // 获取课程信息
    fetchCourse(id) {
      courseApi.queryInfoById(id).then(response => {
        this.courseInfo = response.data.item
        // 级联选择器回显
        this.courseInfo.subjectIds = [this.courseInfo.subjectParentId, this.courseInfo.subjectId]
      })
    },
    // 修改二级科目children为undefined
    modifySubjectList(data) {
      data.forEach(subject => {
        if (subject.children.length < 1) {
          subject.children = undefined
        } else {
          this.modifySubjectList(subject.children)
        }
      })
      return data
    },
    // 级联选择器改变时
    subjectChanged(value) {
      this.courseInfo.subjectParentId = value[0]
      this.courseInfo.subjectId = value[1]
    },
    // 保存或修改并下一步
    saveAndNext() {
      this.saveBtnDisabled = true
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          this.saveData()
        } else {
          this.$message.warning('请完成必填项')
          this.saveBtnDisabled = false
        }
      })
    },
    // 保存或修改并下一步
    updateAndNext() {
      this.saveBtnDisabled = true
      this.$refs.courseForm.validate((valid) => {
        if (valid) {
          this.updateData()
        } else {
          this.$message.warning('请完成必填项')
          this.saveBtnDisabled = false
        }
      })
    },
    // 下一步
    next() {
      this.$parent.active = 1
    },
    // 保存
    saveData() {
      if (this.courseInfo.cover === '') {
        this.courseInfo.cover = 'https://hsedu-horsen.oss-cn-beijing.aliyuncs.com/cover/default.png'
      }
      courseApi.insert(this.courseInfo).then(response => {
        this.$message.success(response.message)
        // 保存courseId
        this.$parent.courseId = response.data.id
        this.next()
      })
    },
    updateData() {
      courseApi.update(this.courseInfo).then(response => {
        this.$message.success(response.message)
        this.next()
      })
    },
    // 上传头像之前校验
    beforeCoverUpload(file) {
      console.log('选择封面')
      // 判断是否是图片
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isImage = suffix === 'jpeg' || suffix === 'jpg' || suffix === 'webp' || suffix === 'png'
      console.log(isImage)
      // 判断是否小于5MB
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$message.warning('上传图片只支持 JPG/JPEG/WEBP/PNG 格式')
      }
      if (!isLt5M) {
        this.$message.warning('上传图片大小不能超过5MB')
      }
      return isImage && isLt5M
    },
    // 上传成功
    handleCoverSuccess(response) {
      if (response.success) {
        this.courseInfo.cover = response.data.url
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error(response.message)
      }
    },
    // 上传失败
    handleCoverError() {
      console.log('error')
      this.$message.error('HTTP错误 上传文件失败')
    }

  }
}
</script>

<style lang="scss">
@import "~@/assets/css/upload_cover.scss";

.tip {
  color: #8c939d;
  margin-left: 10px;
  font-size: 13px;
}

.tinymce-container {
  position: relative;
  line-height: normal;
}

.editor-custom-btn-container[data-v-0177f75c] {
  top: 2px;
}
</style>
